<template>
  <div class="page shop">
    <van-tabs v-if="!$store.getters.ifShoper" v-model="search.type" @change="searchFunc" color="#517df1" title-active-color="#517df1" title-inactive-color="#9d9d9d">
      <van-tab v-for="(item, index) in nav" :key="index" :name="item.value">
        <template #title> 
          <div style="font-size: 14px; text-align: center;">{{ item.label }}</div>
        </template>
      </van-tab>
    </van-tabs>
    <top-search @search="searchFunc" v-model="search.shopName" bgcolor="#fff"></top-search>
    <div class="top-picker" v-if="$store.getters.ifAdmin || $store.getters.ifAgent">
      <div class="picker-item">
        <span @click="showSelePerson = true">
          <span>{{ search.User }}</span>
          <van-icon name="play" class="trans"/>
        </span>
      </div>
      <top-picker :option="option.sort" v-model="search.sort"></top-picker>
    </div>
    <van-list class="page-content" v-model="page.loading" :finished="page.finished" finished-text="没有更多了" @load="getList">
      <div class="list-item" v-for="(item, index) in list" :key="index">
        <div class="list-group flex-row" style="padding-top: 0.25rem; padding-bottom: 0.25rem; font-size: 14px;">
          <img :src="item.shopPhotBase" style="width: 0.9rem; height: 0.9rem; border-radius: 50%;"/>
          <div style="flex: 1; margin-left: 0.27rem;" class="flex-col">
            <div class="flex-row" style="justify-content: flex-start;">
              <span>{{ item.shopName }}</span>
              <img v-if="item.level > 0" :src="`./img/l${ item.level }.png`" style="width: 0.75rem; height: 0.29rem; margin-left: 0.15rem;"/>
            </div>
            <div style="color: #6e6e6e; font-size: 12px;">门店编号:{{ item.shopId }}</div>
          </div>
          <img :src="'./img/posi.png'" style="width: 0.4rem; height: 0.4rem;"/>
          <div v-if="!$store.getters.ifShoper && !$store.getters.ifIntroducer" style="height: 0.4rem; line-height: 0.4rem; padding-left: 0.25rem; margin-left: 0.25rem; 
            border-left: 1px solid #ededed;" class="font-blue" @click="$router.push({ name: 'Shop-Add', params: item })">修改</div>
            <!-- border-left: 1px solid #ededed;" class="font-blue" @click="shop.showBlank(item)">修改</div> -->
        </div>
        <div class="list-group justify">
          <div class="list-row">
            <span class="label-text">设备数</span>
            <span>{{ item.terminalNum }}</span>
          </div>
          <div class="list-row">
            <span class="label-text">充电宝数</span>
            <span>{{ item.chargerNum }}</span>
          </div>
        </div>
        <div class="list-group justify" v-if="!$store.getters.ifShoper">
          <div class="list-row">
            <span class="label-text">前月流水</span>
            <span>{{ item.liushui[0] }}</span>
          </div>
          <div class="list-row">
            <span class="label-text">上月流水</span>
            <span>{{ item.liushui[1] }}</span>
          </div>
          <div class="list-row">
            <span class="label-text">本月流水</span>
            <span>{{ item.liushui[2] }}</span>
          </div>
        </div>
        <div class="list-group justify" style="padding-top: 0.25rem; padding-bottom: 0.25rem; font-size: 14px;">
          <div class="list-row" v-if="!$store.getters.ifShoper">
            <span @click="$router.push({ name: 'Shop-Manage', query: { shopId: item.shopId } })" class="font-blue">管理员</span>
            <span v-if="!$store.getters.ifIntroducer" @click="closeShop(item)" class="font-org">{{ item.status ? '恢复' : '删除' }}门店</span>
            <span v-if="!$store.getters.ifIntroducer" @click="$router.push({ name: 'Shop-Device', query: { shopId: item.shopId } })" class="font-org">管理设备</span>
            <span @click="$router.push({ name: 'Shop-Order', query: { shopId: item.shopId } })" class="font-blue">订单详情</span>
          </div>
        </div>
      </div>
    </van-list>

    <van-popup v-model="manage.show" position="bottom" :style="{ height: '100%' }">
      <div class="page">
        <van-nav-bar title="管理员信息" left-arrow @click-left="manage.show = false"/>
        <van-form ref="form">
          <van-field readonly label="代理名称"  :value="manage.info.agentName"/>
          <van-field readonly label="代理账号"  :value="manage.info.agentUserName"/>
          <van-field readonly label="代理ID"    :value="manage.info.agentUserId"/>
          <van-field readonly label="管理员名称" :value="manage.info.shopManagerName"/>
          <van-field readonly label="管理员账号" :value="manage.info.shopManagerUserName"/>
          <van-field readonly label="管理员ID"  :value="manage.info.shopManagerId"/>
        </van-form>
        <div style="margin: 1rem 16px 16px;">
          <van-button block type="info" @click="manage.show = false">关闭</van-button>
        </div>
      </div>
    </van-popup>  

    <van-popup v-model="device.show" position="bottom" :style="{ height: '100%' }">
      <div class="page">
        <van-nav-bar title="门店设备" left-arrow @click-left="device.show = false"/>
        <div class="page-content">
          <div class="list-item" v-for="(item, index) in device.list" :key="index">
            <div class="list-group flex-row" style="padding-top: 0.25rem; padding-bottom: 0.25rem;">
              <span class="font-black" style="font-size: 14px; margin-left: 0.28rem;">充电宝机柜</span>
            </div>
            <div class="list-group justify">
              <div class="list-row">
                <span class="label-text">设备编号</span>
                <span class="font-blue">{{ item.equipmentNum }}</span>
              </div>
              <div class="list-row">
                <span class="label-text">上线天数</span>
                <span>{{ item.onlineDays }}</span>
              </div>
            </div>
            <div class="list-group justify" style="padding-top: 0.25rem; padding-bottom: 0.25rem; font-size: 14px;">
              <div class="list-row">
                <span @click="device.shengji(item)" class="font-blue">设备升级</span>
                <span v-if="$store.getters.isAdmin" @click="device.showDetail(item)" class="font-org">弹出设备</span>
                <span @click="device.jiebang(item)" class="font-blue">解绑设备</span>
              </div>
            </div>
          </div>
        </div>
        <div style="background: #fff;">
          <div style="margin: 16px;">
            <van-button block type="info" @click="device.bangding">绑定设备</van-button>
          </div>
        </div>
        <!-- <div style="height: 100px;">
          <van-button block type="info" @click="device.bangding">绑定设备</van-button>
        </div> -->
      </div>
    </van-popup>  

    <device-info ref="device"></device-info>

    <van-popup v-model="order.show" position="bottom" :style="{ height: '100%' }">
      <div class="page">
        <van-nav-bar title="门店订单" left-arrow @click-left="order.show = false"/>
        <van-list class="page-content" v-model="order.page.loading" :finished="order.page.finished" finished-text="没有更多了" @load="order.getList">
          <div class="list-item" v-for="(item, index) in order.list" :key="index">
            <div class="list-group flex-row" style="padding-top: 0.25rem; padding-bottom: 0.25rem;">
              <div class="flex-row">
                <img :src="item.icon" style="width: 0.6rem; height: 0.6rem; border-radius: 50%;"/>
                <span class="font-black" style="font-size: 14px; margin-left: 0.28rem;">{{ item.nick || '无昵称' }}</span>
              </div>
              <span class="font-gray" style="font-size: 14px;">用户ID:{{ item.userId }}</span>
            </div>
            <div class="list-group">
              <div class="list-row">
                <div class="list-row" style="width: 50%;">
                  <span class="label-text">订单编号</span>
                  <span>{{ item.orderId }}</span>
                </div>
                <div class="list-row" style="width: 50%;">
                  <span class="label-text">订单费用</span>
                  <span class="font-warn">{{ item.realExpense || item.realExpense == 0 ? item.realExpense + '元' : $store.getters.dictTrans.order[item.orderStatus] }}</span>
                </div>
              </div>
              <div class="list-row">
                <div class="list-row" style="width: 50%;">
                  <span class="label-text">设备编号</span>
                  <span>{{ item.equipmentSn }}</span>
                </div>
                <div class="list-row" style="width: 50%;">
                  <span class="label-text">充电宝编号</span>
                  <span>{{ item.chargerSn }}</span>
                </div>
              </div>
              <div class="list-row">
                <span class="label-text">租借地点</span>
                <span>{{ item.shopName }}({{ item.rentShopId }})</span>
              </div>
            </div>
            <div class="list-group">
              <div class="list-row">
                <span class="label-text">租借时间</span>
                <span>{{ item.rentTime }}</span>
              </div>
              <div class="list-row" v-if="item.returnTime">
                <span class="label-text">归还时间</span>
                <span>{{ item.returnTime }}</span>
              </div>
              <div class="list-row" v-if="item.payTime">
                <span class="label-text">付款时间</span>
                <span>{{ item.payTime }}</span>
              </div>
            </div>
          </div>
        </van-list>
      </div>
    </van-popup>  

    <van-popup v-model="shop.show" position="bottom" :style="{ height: '100%' }">
      <add-shop v-if="shop.show" ref="addShop" @close="shop.onClose"></add-shop>
    </van-popup>

    <sele-person v-model="showSelePerson" @submit="seleUser"></sele-person>

    <van-action-sheet v-model="device.showAction" :actions="device.actions" @select="device.selectAction" 
      cancel-text="取消" @cancel="device.showAction = false"/>

    <router-view></router-view>

  </div>
</template>

<script>
import DeviceInfo from '../Device/DeviceInfo.vue';
import AddShop from '../Mine/AddShop.vue';
export default {
  components: { DeviceInfo, AddShop },
  data() {
    return {
      nav: [
        { label: '有设备', value: 1 },
        { label: '无设备', value: 2 },
        { label: '预警门店', value: 3 },
        { label: '已删除门店', value: 4 }
      ],

      search: {
        type: 1,
        shopName: '',
        userId: this.$store.state.userInfo.userId,
        User: '全部门店',
        sort: 0
      },

      page: {
        page: 1,
        size: 10,
        loading: false,
        finished: true
      },

      list: [],

      option: {
        sort: [
          { label: '当月流水从高到低', value: 0 },
          { label: '当月流水从低到高', value: 1 },
          { label: '上月流水从高到低', value: 2 },
          { label: '上月流水从低到高', value: 3 },
          { label: '前月流水从高到低', value: 4 },
          { label: '前月流水从低到高', value: 5 },
          { label: '充电宝数从高到低', value: 6 },
          { label: '充电宝数从低到高', value: 7 }
        ]
      },

      manage: {
        show: false,
        info: {},
        showBlank: (shopId) => {
          this.$axios.get('/api/ShopManageController/shopOwnership', { 
            shopId 
          }).then(res => {
            this.manage.info = res;
            this.manage.show = true;
          });
        }
      },

      device: {
        show: false,
        list: [],
        shopId: '',
        showAction: false,
        actions: [
          { name: '普通设备' },
          { name: '新48口（双二维码设备）' }
        ],
        selectAction: (obj) => {
          if(obj.name == '新48口（双二维码设备）') {
            this.$dialog({ title: '提示', message: '请扫描设备右侧二维码！' }).then(() => {
              this.$tool.scanEquipment().then(rcode => {
                this.$dialog({ title: '提示', message: '请扫描设备左侧二维码！' }).then(() => {
                  this.saoma(result => {  
                    let lcode = result.split('=')[1];
                    this.device.bang(rcode + '&&' + lcode);
                  });
                });
              });
            });
          } else {
            this.$tool.scanEquipment().then(res => {
              this.device.bang(res);
            });
          }
        },
        bang: (snList) => {
          let userId = this.$store.state.userInfo.userId;
          this.$axios.post('/api/chargerPlaEquipmentController/shopBindingDevice', {
            query: { snList, shopId: this.device.shopId, userId }
          }).then(res => {
            this.$toast('设备绑定成功！');
            this.device.showAction = false;
            this.device.showBlank(this.device.shopId);
          });
        },
        showBlank: (shopId) => {
          // let userId = this.$store.state.userInfo.userId;
          // let vague = 2;
          // this.$axios.get('/api/chargerPlaEquipmentController/getChargerPlaEquipmentList', {
          //   userId, vague, shopId, page: 1, size: 100
          // }).then(res => {
          //   this.device.list = res || [];
          //   this.device.show = true;
          // });
          this.device.shopId = shopId;
          this.$axios.get('/api/ShopManageController/getEquipmentByShopId', {
            shopId
          }).then(res => {
            this.device.list = res || [];
            // if (this.device.list)
            this.device.show = true;
          });
        },
        shengji: (item) => {
          this.$dialog.confirm({ message: `设备升级后会关闭设备大部分提示音，设备升级过程中请保持通电，确定现在要对设备进行升级吗？` }).then(() => {
            this.$axios.get('/api/chargerPlaEquipmentController/terminalVersion', {
              sn: item.equipmentNum
            }).then(res => {
              if(res.canUpdate) {
                this.$axios.get('/api/chargerPlaEquipmentController/terminalUpdate', {
                  sn: item.equipmentNum
                }).then(() => {
                  this.$toast('正在为该设备升级，请保证设备在升级过程中处于通电状态');
                });
              }
            });
          })
        },
        jiebang: (item) => {
          let shopId = this.device.shopId;
          this.$dialog.confirm({
            message: `您确认要解绑 ${ item.equipmentNum } 吗？`
          }).then(() => {
            this.$axios.post('/api/chargerPlaEquipmentController/unbindSnByshop', { 
              query: { snList: item.equipmentNum, shopId } 
            }).then(() => {
              this.$toast(`解绑成功！`);
              this.device.showBlank(shopId);
            });
          });
        },
        showDetail: (item) => {
          this.$refs.device.showBlank({
            shopName: item.shopName,
            equipmentNum: item.equipmentNum,
            shopPhotUrl: item.shopPhotUrl,
            createTime: item.createTime
          });
        },
        bangding: () => {
          this.device.showAction = true;
        }
      },

      order: {
        show: false,
        list: [],
        shopId: '',
        page: {
          page: 1,
          size: 10,
          loading: false,
          finished: false
        },
        showBlank: (shopId) => {
          this.order.shopId = shopId;
          this.order.show = true;
          this.order.page = { page: 1, size: 10, loading: false, finished: false };
          this.order.list = [];
          this.order.getList();
        },
        getList: () => {
          let sPage = JSON.parse(JSON.stringify(this.page));
          let page = sPage.page, size = sPage.size;
          this.order.page.loading = true;
          let shopId = this.order.shopId;
          let query = { page, size, shopId };

          this.$axios.get('/api/orderFormController/manageOrderByShopId', query).then(res => {
            let json = res || {}; 
            let list = json.list || [];
            this.order.list.push( ...list );
            let finished = json.isLastPage ? true : false;

            this.order.page = { ...sPage, page: sPage.page + 1, loading: false, finished };
          }).catch(() => {
            this.order.page.loading = false;
            this.order.page.finished = true;
          });
        }
      },

      showSelePerson: false,

      shop: {
        show: false,
        onClose: () => {
          this.shop.show = false;
        },
        showBlank: (item) => {
          this.shop.show = true;
          this.$nextTick(() => {
            this.$refs.addShop.setValue(item);
          });
        }
      }
    };
  },
  methods: {
    getList() {
      let sPage = JSON.parse(JSON.stringify(this.page));
      let page = sPage.page, size = sPage.size;
      this.page.loading = true;
      
      let search = JSON.parse(JSON.stringify(this.search));
      let sort = [ 'month1 desc', 'month1 asc', 'month2 desc', 'month2 asc', 'month3 desc', 'month3 asc', 'chargerNum desc', 'chargerNum asc' ][search.sort];
      // content字段名不对
      let query = { ...search, sort, page, size };
      delete query.User;

      this.$axios.get('/api/ShopManageController/getShopManageList', query).then(res => {
        if(search.type != this.search.type) return ;
        let json = res || {}; 
        let list = json.list || [];
        list.forEach(ele => {
          let liushui =  [];
          liushui = [ ele.month3, ele.month2, ele.month1 ];
          ele.level = this.getLevel(liushui);
          ele.levelList = this.getLevalList(liushui);
          ele.liushui = liushui;
        });
        this.list.push( ...list );
        let finished = json.isLastPage ? true : false;

        this.page = { ...sPage, page: sPage.page + 1, loading: false, finished };
      }).catch(() => {
        this.page = { ...sPage, loading: false, finished: true };
      });
    },
    searchFunc() {
      this.page = { page: 1, size: 10, loading: false, finished: false };
      this.list = [];
      this.getList();
    },
    getLevel(liushui) {
      let day = new Date().getDate();
      let total = liushui[0] + liushui[1] + liushui[2];
      let average = 0;
      if ( total < 60 ) { return 0 }
      if ( day < 5 ) {
        average = Math.floor( (liushui[0] + liushui[1]) / 2 );
      } else {
        average = Math.floor( (liushui[0] + liushui[1] + ((liushui[2]/day) * 30)) / 3 );
      } 
      return this.levelNum(average);
    },
    getLevalList(liushui) {
      let list = liushui.slice(0);
      let level = [];  
      let day = new Date().getDate();
      list[2] = (list[2]/day) * 30;
      list.forEach((ele) =>  {
        level.push( this.levelNum(ele) );
      });
      return level;
    },
    levelNum(average) {
      if ( average < 60 ) return 0;
      else if ( average < 100 ) return 1;
      else if ( average < 200 ) return 2;
      else if ( average < 500 ) return 3;
      else if ( average < 1000 ) return 4;
      else return 5;
    },
    seleUser(user) {
      this.search = { ...this.search, userId: user.userId, User: user.nick + '名下门店' };
      this.searchFunc();
    },
    closeShop(item) {
      this.$dialog.confirm({ message: `您确认要${ item.status ? '恢复' : '删除' } ${ item.shopName } 吗？` }).then(() => {
        let shopManageIdList = item.shopId, status = item.status ? 0 : 1;
        this.$axios.post('/api/ShopManageController/nableDisableeShopList', { 
          query: { shopManageIdList, status } 
        }).then(() => {        
          this.$toast(`${ item.status ? '恢复' : '删除' }成功！`);
          this.searchFunc();
        });
      });
    },
    goto(shop) {
      let config = this.$store.state.config;
      window.wx.config({ ...config, debug: false, jsApiList: [ 'scanQRCode', 'chooseImage', 'uploadImage', 'getLocation', 'openLocation' ] });
      window.wx.openLocation({
        latitude: shop.latitude, // 纬度，浮点数，范围为90 ~ -90
        longitude: shop.longitude, // 经度，浮点数，范围为180 ~ -180。
        name: shop.shopName, 
        address: shop.shopSite, // 地址详情说明
        scale: 23,
        infoUrl: ''
      });
    }
  },
  created() {
    if (this.$store.getters.ifShoper || this.$store.getters.ifIntroducer) this.nav = this.nav.slice(0, 2);
  },
  mounted() { 
    // this.searchFunc();
  }
};
</script>

<style lang="less">
</style>
